<?php
/**
 * 提现
 */

namespace app\controller\v1;


use app\model\UserWithdrawalModel;
use app\model\WithdrawalLog;
use app\Request;
use app\services\AliPayServices;
use app\services\BankServices;
use think\facade\Db;

class Withdrawal
{
    /**
     *
     * 提现
     * @param Request $request
     * @return mixed
     */
    public function Withdrawal(Request $request,WithdrawalLog $withdrawalLog)
    {

        return $withdrawalLog->withdrawal($request);

    }
    /**
     *
     * 提现
     * @param Request $request
     * @return mixed
     */
    public function WithdrawalLog(Request $request,WithdrawalLog $withdrawalLog)
    {

        return $withdrawalLog->WithdrawalLog($request);

    }




    /**
     * 后台提现
     * @param Request $request
     * @param UserWithdrawalModel $model
     * @return mixed
     */
    public function executeAdmin(Request $request, UserWithdrawalModel $model)
    {
        [$id, $channel] = $request->getMore([
            ['id', ''],
            ['channel', '']
        ], true);
        if (empty($id) || empty($channel))
            return app('json')->json_error('参数错误，提现失败');
        $info = $model->where(['status' => 0, 'channel' => $channel, 'id' => $id])->findOrEmpty();
        if (empty($info))
            return app('json')->json_error('提现信息不存在');
        try {
            switch ($channel) {
                case 1; // 支付宝提现
                    return AliPayServices::instance()->uid($info['uid'])->data($info->toArray())->adminWithdrawal();
                    break;
                case 2://微信提现
                    break;
                case 3: //银行卡提现
                    return BankServices::instance()->uid($info['uid'])->data($info->toArray())->adminWithdrawal();
                    break;
            }
        } catch (\Exception $e) {
            return app('json')->json_error('提现失败');
        }
    }


    /**
     * 提现配置
     * @param Request $request
     * @param WithdrawalLog $model
     * @return mixed
     */
    public function withdrawalConfig(Request $request, WithdrawalLog $model)
    {
        try {
            $config = get_config(2);
            $today_transfer_num = $config['TRANSFERMAXDAYNUM']; // 每日最大提现次数
            $data['transfer_min_amount'] = $config['AGENT_REFLECT_MONEY']; // 单笔提现最小金额
            $data['transfer_max_amount'] = $config['TRANSFERMAX']; // 单笔提现最大金额
            $today_tx = $model->where('user_id', $request->user_id)->whereTime('create_at', 'today')->count('id'); // 今日提现次数
            $data['today_transfer_count'] = $today_transfer_num - $today_tx <= 0 ? 0 : $today_transfer_num - $today_tx; // 今日剩余提现次数
            $data['transfer'] = 5;
            return app('json')->json_success('获取成功', $data);
        } catch (\Exception $e) {
            return app('json')->json_error('获取失败'.$e->getMessage());
        }
    }
}